<?php

namespace App\Controller\Admin;

use Gregwar\Captcha\CaptchaBuilder;
use Hyperf\Context\ApplicationContext;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\Redis\RedisFactory;

#[Controller(prefix: '/admin/Captcha')]
class CaptchaController extends BaseController {

    /**
     * 生成验证码图片
     */
    #[GetMapping(path: 'create')]
    public function create(): array {
        $builder = new CaptchaBuilder(4);
        $builder->build();

        // 保存验证码字符串到Session中
        $phrase = $builder->getPhrase();
        $redis  = ApplicationContext::getContainer()->get(RedisFactory::class)->get('default');
        $uuid   = uniqid();
        $redis->set($uuid, $phrase, 300);

        // 输出验证码图片
        return $this->buildSuccess(['img' => $builder->inline(), 'uuid' => $uuid]);
    }
}
